package com.infodeli.admin.service.impl;

import com.infodeli.admin.entity.InfoAttrSelectEntity;
import com.infodeli.admin.entity.InfoInputTypeEntity;
import com.infodeli.admin.service.InfoAttrSelectService;
import com.infodeli.admin.service.InfoInputTypeService;
import com.infodeli.admin.vo.InfoAttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.infodeli.common.utils.PageUtils;
import com.infodeli.common.utils.Query;

import com.infodeli.admin.dao.InfoAttrDao;
import com.infodeli.admin.entity.InfoAttrEntity;
import com.infodeli.admin.service.InfoAttrService;

import javax.sound.sampled.Line;


@Service("infoAttrService")
public class InfoAttrServiceImpl extends ServiceImpl<InfoAttrDao, InfoAttrEntity> implements InfoAttrService {

    @Autowired
    InfoInputTypeService infoInputTypeService;

    @Autowired
    InfoAttrSelectService infoAttrSelectService;

    /**
     * 保存 infoAttr
     */
    @Override
    public void save(InfoAttrVo infoAttrVo) {
        InfoAttrEntity infoAttrEntity = new InfoAttrEntity();
        BeanUtils.copyProperties(infoAttrVo, infoAttrEntity);
        this.save(infoAttrEntity); // 1、保存 infoAttrEntity
        infoAttrVo.setAttrId(infoAttrEntity.getAttrId());
        if("selector".equals(infoAttrVo.getType())) {

            List<InfoAttrSelectEntity> list = new ArrayList<>();
            int i = 0;
            for (String value : infoAttrVo.getSelectValue()) {
                InfoAttrSelectEntity infoAttrSelectEntity = new InfoAttrSelectEntity();
                infoAttrSelectEntity.setAttrId(infoAttrVo.getAttrId());
                infoAttrSelectEntity.setSelectValue(value);
                infoAttrSelectEntity.setShowStatus(1);
                infoAttrSelectEntity.setIcon("");
                infoAttrSelectEntity.setSort(i);
                list.add(infoAttrSelectEntity);
                i++;
            }
            infoAttrSelectService.saveBatch(list);
        }
    }

    @Override // 更新 showStatus
    public void updateShowStatus(Long attrId, Integer showStatus) {
        InfoAttrEntity entity = new InfoAttrEntity();
        entity.setAttrId(attrId);
        entity.setShowStatus(showStatus);
        this.updateById(entity);
    }

    @Override // 基本的 分页查询
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<InfoAttrEntity> page = this.page(
                new Query<InfoAttrEntity>().getPage(params),
                new QueryWrapper<InfoAttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageVoByCatId(Map<String, Object> params, Long catId){
        QueryWrapper<InfoAttrVo> wrapper = new QueryWrapper<>();
        wrapper.eq("cat_id", catId);
        String attrName = (String) params.get("key");
        if(attrName != null && !"".equals(attrName)){
            wrapper.like("attr_name", attrName);
        }
        IPage<InfoAttrVo> page = baseMapper.queryPageVo(
                new Query<InfoAttrEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }


    /**
     * 根据 catId 查询对应的 信息属性
     * @param params 分页数据、关键字key
     * @param catId 信息种类catId
     * @return
     */
    @Override
    public PageUtils queryPageByCatId(Map<String, Object> params, Long catId) {
        // 在这里按照 catId 和 分页条件 进行查询
        QueryWrapper<InfoAttrEntity> wrapper = new QueryWrapper<>(); // 处理 查询条件
        wrapper.eq("cat_id", catId);

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.like("attr_name", key);
        }

        IPage<InfoAttrEntity> page = this.page(
                new Query<InfoAttrEntity>().getPage(params), // 处理 分页数据
                wrapper
        );

        // 对 获取到的 attr 填充 可选值、type
        PageUtils pageUtils = new PageUtils(page);
        List<?> list = pageUtils.getList();
        if(list == null || list.size() == 0){
            return pageUtils;
        }

        Map<Long, String> typeMap = getTypeMap(list);

        Map<Long, List<String>> selectMap = getSelectMap(list);

        List<InfoAttrVo> vos = getInfoAttrVos(list, typeMap, selectMap);

        pageUtils.setList(vos);

        return pageUtils;
    }

    @Override
    public List<InfoAttrVo> listByCatId(Long catId) {
        QueryWrapper<InfoAttrEntity> wrapper = new QueryWrapper<InfoAttrEntity>().eq("cat_id", catId);
        List<InfoAttrEntity> list = this.list(wrapper);
        if(list == null || list.size() == 0){
            // todo: 没有数据，抛出异常
            return null;
        }
        Map<Long, String> typeMap = getTypeMap(list);
        Map<Long, List<String>> selectMap = getSelectMap(list);
        List<InfoAttrVo> infoAttrVos = getInfoAttrVos(list, typeMap, selectMap);
        return infoAttrVos;
    }



    public List<InfoAttrVo> getInfoAttrVos(List<?> list, Map<Long, String> typeMap, Map<Long, List<String>> selectMap){
        // 开始 填充
        List<InfoAttrVo> vos = list.stream().map(entity -> {
            InfoAttrVo vo = new InfoAttrVo();
            BeanUtils.copyProperties(entity, vo);
            Long attrId = ((InfoAttrEntity) entity).getAttrId();
            Long typeId = ((InfoAttrEntity) entity).getTypeId();
            String typeName = typeMap.get(typeId);
            List<String> selectValues = selectMap.get(attrId);
            vo.setType(typeName);
            vo.setSelectValue(selectValues);
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }

    public Map<Long, String> getTypeMap(List<?> list) {// 获取 type
        List<InfoInputTypeEntity> infoInputTypeEntities = infoInputTypeService.list();
        Map<Long, String> typeMap = new HashMap<>();
        for (InfoInputTypeEntity entity : infoInputTypeEntities) {
            typeMap.put(entity.getTypeId(), entity.getTypeName());
        }
        return typeMap;
    }

    public Map<Long, List<String>> getSelectMap(List<?> list){
        // 获取 可选值 selectValue
        List<Long> attrIds = list.stream().map(entity -> {
            return ((InfoAttrEntity) entity).getAttrId();
        }).collect(Collectors.toList());
        List<InfoAttrSelectEntity> infoAttrSelectEntities = infoAttrSelectService.listByAttrId(attrIds);
        Map<Long, List<String>> selectMap = new HashMap<>();
        infoAttrSelectEntities.forEach(entity->{
            if(selectMap.get(entity.getAttrId()) == null){
                selectMap.put(entity.getAttrId(), new ArrayList<String>());
            }
            selectMap.get(entity.getAttrId()).add(entity.getSelectValue());

        });
        return selectMap;
    }

}